/**
 * 
 */
package com.ikas.ai.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Administrator
 * 
 */
public class HttpConnectionUtil {

	private static class HttpUtilHolder{
		public final static HttpConnectionUtil instance = new HttpConnectionUtil();
	}
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
        JSONObject requestUdeskParams = new JSONObject();
        requestUdeskParams.put("url", "http://dc.dftcmedia.com:5000/api/deviceOnline/"); // 东方天呈在线率接口
        requestUdeskParams.put("method", "GET");
        JSONObject jsonObj = HttpConnectionUtil.getInstance().invokeCommonConnection(requestUdeskParams).getJSONObject("success");
//		Map<String, Object> joResult = (Map<String, Object>) jsonObj.get("success");
        System.out.println(jsonObj.toJSONString());
	}

	public static HttpConnectionUtil getInstance(){
		return HttpUtilHolder.instance;
	}
	
	/**
	 * http客户端长连接请求工具类
	 * 
	 */
    public JSONObject invokeCommonConnection(JSONObject params) throws Exception {
        JSONObject responseResult = new JSONObject();
        JSONObject requestParams = params.getJSONObject("params");
        String url = params.getString("url");
        String method = params.getString("method");
        URL object = new URL(url);
        HttpURLConnection con = (HttpURLConnection) object.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestProperty("accept", "*/*");
        con.setRequestProperty("connection", "Keep-Alive");//保持长连接
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestMethod(method);
        //设置连接和读取数据超时时间分别为1分钟和2分钟
        con.setConnectTimeout(60000);
        con.setReadTimeout(120000);
        if (requestParams != null) {
            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "utf-8");
            wr.write(requestParams.toString());
            wr.flush();
        }
        // 显示请求返回的内容
        StringBuilder sb = new StringBuilder();
        int HttpResult = con.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK || HttpResult == HttpURLConnection.HTTP_CREATED) {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            responseResult.put("success", JSONObject.parseObject(sb.toString()));

        } else {
            responseResult.put("error", con.getResponseMessage());
        }
        return responseResult;
    }
}
